package net.dgg.zz.credential.qualification.controller;

import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.iboss.base.util.datatable.domain.DataTableResponse;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.files.service.AnnexService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.utils.ExcelTool;
import net.dgg.zz.common.utils.OrderHandleUtils;
import net.dgg.zz.credential.certificateType.service.CertificateTypeService;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.qualification.entity.Qualification;
import net.dgg.zz.credential.qualification.service.QualificationService;
import net.dgg.zz.credential.storageCapacity.service.StorageCapacityService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/zs/credential/qualification")
public class QualificationController extends DggBaseController {
    @Autowired
    private QualificationService qualificationService;

    @Autowired
    private CertificateTypeService certificateTypeService;

    @Autowired
    private AnnexService annexService;

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private OrganizationManager organizationManager;

    @Autowired
    private TranslateUtil translateUtil;

    @Autowired
    private CommonService commonService;
    @Autowired
    private StorageCapacityService storageCapacityService;

    /**
     * 显示资质页面 certificateStatus    overdueStatuss
     *
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model, @RequestParam Map params) {
        Iterator<Map.Entry<String, String>> map = params.entrySet().iterator();
        while (map.hasNext()) {
            Map.Entry<String, String> entry = map.next();
            model.addAttribute(entry.getKey(), entry.getValue());
        }
        int[] types = {2, 3, 4};
        params.put("types", types);
        qualificationService.findZiDian(model, params);
        return "zzsc/credential/qualification/index";
    }


    /**
     * 资质信息列表数据
     *
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("find_page_data")
    @ResponseBody
    public DataTableResponse findDataWithPage(@RequestParam Map params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request); //获取datatable参数
            //查询user
            UserEntity user = sessionManager.getCurrentUser();
            if (params.containsKey("haveAuthority") && params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            params.put("page", r.getPage());//获取当前页
            params.put("limit", r.getLength());//获取每页条数
            List<Map> list = qualificationService.queryDataWithPage(params);
            String[] column = {"certificateArea", "areaProvince", "applicationScope", "certificateStatus", "overdueStatus", "certificateLevel"};//需要业态
            list = translateUtil.translateList(column, list);
            int count = Integer.parseInt(params.get("count").toString());//总条数
            return new DataTableResponse(r.getDraw(), count, count, list, "");//返回数据
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return new DataTableResponse(0, 0, 0, null, "查询失败");//返回数据
        }
    }

    /**
     * 根据id查询资质全部信息
     *
     * @param id
     * @return
     */
    @RequestMapping("find_by_id")
    @ResponseBody
    public DggRestResponse findById(Long id) {
        try {
            Map map = qualificationService.findById(id);
            return this.getSuccessResponse(map);
        } catch (Exception e) {
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 显示修改与增加界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("edit_page")
    public String showEditPage(Long id, Long specialtyId, Model model, Map params) {
        int[] types = {1, 4, 5};
        params.put("types", types);
        qualificationService.findZiDian(model, params);
        if (null != id) {//修改数据
            Map qualification = qualificationService.findById(id);
            model.addAttribute("certificateArea", qualification.get("certificateArea"));
            String[] column = {"areaProvince", "certificateArea", "certificateStatus", "overdueStatus"};//需要转化的字段
            qualification = translateUtil.translateObject(column, qualification);
            model.addAttribute("qualification", qualification);
            Map nameMap = new HashMap();
            nameMap.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            nameMap.put("certificateName", qualification.get("certificateType"));
            List<Map> certificateTypes = certificateTypeService.getCertificateType(nameMap);
            nameMap.put("certificateName", "");
            nameMap.put("parentId", certificateTypes.get(0).get("id"));
            List<Map> certificateNames = certificateTypeService.getCertificateType(nameMap);
            model.addAttribute("nameList", certificateNames);
            model.addAttribute("changeNames", (String) qualification.get("certificateMajorId"));
            model.addAttribute("specialtyId", specialtyId);
           /* String fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX+"_"+qualification.get("id")+"_credential";
            List<Annex> files = annexService.findFile(fileId);
            if (null != files) {
                for (Annex file : files) {
                    file.setFilepath(fastdfsHost + file.getFilepath());
                }
            }
            model.addAttribute("files",files);*/
            model.addAttribute("qualificationId", qualification.get("id"));
            model.addAttribute("saveType", "modify");
        } else {
            model.addAttribute("saveType", "add");
            model.addAttribute("qualificationId", DggKeyWorker.nextId());
        }
        return "zzsc/credential/qualification/edit";
    }

    /**
     * 修改或增加资质信息
     *
     * @param params
     * @return
     */
    @RequestMapping("save_edit")
    @ResponseBody
    public DggRestResponse saveEidit(@RequestParam Map params) {
        try {
            qualificationService.saveUpdate(params);
        } catch (CertificateExcption ce) {
            logger.error(ce.getMessage(), ce);
            return this.getFailResponse(ce.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误，请联系管理员");
        }
        return this.getSuccessResponse("保存成功");
    }


    /**
     * 今日录入量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_today_entry")
    @ResponseBody
    public DggRestResponse countTodaysEntry(@RequestParam Map params) {
        try {
            UserEntity user = sessionManager.getCurrentUser();
            if (params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            params.put("startTime", adf.format(date) + " 00:00:00");
            params.put("endTime", adf.format(date) + " 23:59:59");
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            return this.getFailResponse("操作失败，请联系管理员！");
        }

    }

    /**
     * 资质总量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_entry_total")
    @ResponseBody
    public DggRestResponse countEntryTotal(@RequestParam Map params) {
        try {
            UserEntity user = sessionManager.getCurrentUser();
            if (params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 预订量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_bookings")
    @ResponseBody
    public DggRestResponse countBookings(@RequestParam Map params) {
        try {
            UserEntity user = sessionManager.getCurrentUser();
            if (params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            params.put("certificateStatus", CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 过期总数量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_stale_total")
    @ResponseBody
    public DggRestResponse countStaleTotal(@RequestParam Map params) {
        try {
            if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
                params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
            }
            params.put("aptitudeStatus", CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FIVE);
            params.put("overdueStatus", CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_TWO);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 本地适用资质量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_native_total")
    @ResponseBody
    public DggRestResponse countNativeTotal(@RequestParam Map params) {
        try {
            UserEntity user = sessionManager.getCurrentUser();
            if (params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            params.put("applicationScope", CredentialConstant.LOCAL);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 本地适用资质量
     *
     * @param params
     * @return
     */
    @RequestMapping("get_natiorwide_total")
    @ResponseBody
    public DggRestResponse countNationwideTotal(@RequestParam Map params) {
        try {
            UserEntity user = sessionManager.getCurrentUser();
            if (params.get("haveAuthority").equals("true")) {
                if (StringUtils.isEmpty((String) params.get("signOrgId"))) {
                    params.remove("signOrgId");
                }
            } else {
                Long orgid = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
                if (orgid != null) {
                    params.put("signOrgId", orgid);
                } else {
                    params.put("signOrgId", user.getOrgId());
                }
            }
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            params.put("applicationScope", CredentialConstant.NATIONWIDE);
            Long count = qualificationService.countPandectTotal(params);
            return this.getSuccessResponse(count);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * 导出Excel
     *
     * @param params
     * @param request
     * @param response
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("export_bag_data")
    public void exportBagData(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) throws ParseException {
        String fileName = "";
        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = df.format(now);
        fileName = "资质信息" + dateStr + ".xls";
        String[] key = {"signOrgName", "id", "certificateNo", "companyName", "certificateExpiryTime", "certificateType", "certificateName", "certificateLevel", "receiptPrice", "certificateStatus", "overdueStatus", "certificateArea", "applicationScope"};
        String[] title = {"所属事业部", "资质系统ID", "资质编号", "资质所属企业", "资质有效期", "资质类型", "资质名称", "资质等级", "成本价格（元）", "资质状态", "超期情况", "地区", "适用范围"};

        List<Map> mList = qualificationService.queryDataWithPage(params);
        String[] column = {"certificateArea", "areaProvince", "applicationScope", "certificateStatus", "overdueStatus", "certificateLevel"};
        mList = translateUtil.translateList(column, mList);

        ExcelTool.createN(fileName, title, key, mList, response);
    }

    /**
     * 显示详情界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("details_page")
    public String showDetailsPage(Long id, Model model) {
        Map qualification = qualificationService.findById(id);
        String[] column = {"certificateArea", "areaProvince", "applicationScope", "certificateStatus", "certificateLevel"};//需要业态
        qualification = translateUtil.translateObject(column, qualification);
        model.addAttribute("qualification", qualification);
//        String fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX+"_"+qualification.get("id")+"_credential";
//        List<Annex> files = annexService.findFile(fileId);
//        if (null != files) {
//            for (Annex file : files) {
//                file.setFilepath(fastdfsHost + file.getFilepath());
//            }
//        }
//        model.addAttribute("files",files);
        return "zzsc/credential/qualification/details";
    }


    /*
     * @Author zsx
     * @Date 2018-09-05 07:09:12
     * @Description 分页查询资质过期预警
     * @param params
     * @param request
     * @return DataTableResponse
     */
    @RequestMapping("get_stale_data")
    @ResponseBody
    public DataTableResponse queryDataWithPage(@RequestParam Map params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request); //获取datatable参数
            params.put("page", r.getPage());//获取当前页
            params.put("limit", r.getLength());//获取每页条数
            params.put("newData", new Date());
//            List<Map> list = qualificationService.queryDataWithPage(params);
            List<Map> list = qualificationService.findExpirationWarningWithPage(params);
            int count = Integer.parseInt(params.get("count").toString());//总条数
            return new DataTableResponse(r.getDraw(), count, count, list, "");//返回数据
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new DataTableResponse(0, 0, 0, null, "服务器错误，请联系管理员!");//返回数据
        }
    }


    /**
     * <p>@Description 匹配时查询的资质列表数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/29 0029 15:29 创建时间</p>
     * <p>@return</p>
     */
    @NLog()
    @RequestMapping("/find_match_data")
    @ResponseBody
    public net.dgg.zz.common.utils.DataTableResponse findMatchData(@RequestParam Map params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request);
            params.put("page", r.getPage());//获取当前页
            params.put("limit", r.getLength());//获取每页条数
            List<Qualification> generalCertificates;
            String matchFlag = "";
            if (net.dgg.zz.common.utils.StringUtils.isNotEmpty(params.get("matchFlag"))) {//这里表示证书匹配的搜索传了条件进来
                matchFlag = params.get("matchFlag").toString();
            }
            if ("0".equals(matchFlag)) {//表示初始化进来
                generalCertificates = new ArrayList<>();
                params.put("count", 0);
                return new net.dgg.zz.common.utils.DataTableResponse().data(params, generalCertificates);
            } else {//其他情况进入
                OrderHandleUtils.getOrderCol(r, params, null);
                params.put("generalCredentialStatus", CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE);//查未使用的
                params.put("overdueStatus", CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE);//查未超期
                //查本事业部的
                params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
                generalCertificates = qualificationService.findMatchData(params);
                String[] transColum = {"certificateArea", "certificateCategory", "certificateToThree", "applicationScope", "certificateLevel"};//翻译
                generalCertificates = translateUtil.translateList(transColum, generalCertificates);//翻译
                return new net.dgg.zz.common.utils.DataTableResponse().data(params, generalCertificates);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 证书总览：证书库容
     */
    @NLog
    @RequestMapping("/wanrning_count")
    @ResponseBody
    public DggRestResponse warningCount(@RequestParam Map params, HttpServletRequest request) {
        try {
            params.put("generalType", CredentialConstant.ZZ_CREDENTIAL);
            List<Map> count = storageCapacityService.generalCredentialWarningCount(params);
            return this.getSuccessResponse(count);
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }
}